<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="24" class="custom-title-box">
        <div class="custom-info-title">
          {{getTitleByName(nameOfPermission)}}列表查询
          <el-button link @click="delFav()" style="margin-bottom: 5px;" v-if="userFavorites?.length > 0">
            <svg-icon icon-class="stars" color="#E6A23C" />
          </el-button>
          <el-button link @click="addFav()" style="margin-bottom: 5px;" v-else>
            <svg-icon icon-class="star" />
          </el-button>
        </div>
        <div>
          <el-button v-waves type="success" icon="Search" @click="handleFilter">
            查询
          </el-button>
          <el-button icon="Refresh" @click="handleResetQuery">
            重置
          </el-button>
        </div>
      </el-col>
    </el-row>
    <div class="filter-container">
      <el-form :inline="true" ref="listQuery" :model="listQuery" class="demo-form-inline">
        <el-form-item label="审批模版类型" prop="approveType">
          <el-radio-group v-model="listQuery.approveType">
            <el-radio-button label="" key="">全部</el-radio-button>
            <el-radio-button v-for="(item,index) in getEnumList('ApproveType')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="approveCode" label="审批模版编码">
          <InputTagDialog v-model="listQuery.approveCode" placeholder="审批模版编码" title="填写审批模版编码" />
        </el-form-item>
        <el-form-item prop="approveName" label="审批模版名称">
          <el-input v-model="listQuery.approveName" placeholder="审批模版名称" @keyup.enter="handleFilter" />
        </el-form-item>
        <el-form-item prop="module" label="系统模块">
          <el-select v-model="listQuery.module" placeholder="系统模块" clearable filterable>
            <el-option key="" label="全部" value="" />
            <el-option v-for="item in approveModuleArr" :key="item.key" :label="item.value" :value="item.key"/>
          </el-select>
          <!--
          <el-radio-group v-model="listQuery.module">
            <el-radio-button label="" key="">全部</el-radio-button>
            <el-radio-button v-for="(item,index) in approveModuleArr" :label="item.key" :key="index">{{item.value}}</el-radio-button>
          </el-radio-group>
          -->
        </el-form-item>
        <el-form-item prop="business" label="业务模块">
          <el-select v-model="listQuery.business" placeholder="业务模块" clearable filterable>
            <el-option key="" label="全部" value="" />
            <el-option v-for="item in approveBusinessArr" :key="item.key" :label="item.value" :value="item.key"/>
          </el-select>
          <!--
          <el-radio-group v-model="listQuery.business">
            <el-radio-button label="" key="">全部</el-radio-button>
            <el-radio-button v-for="(item,index) in approveBusinessArr" :label="item.key" :key="index">{{item.value}}</el-radio-button>
          </el-radio-group>
          -->
        </el-form-item>
        <el-form-item prop="state" label="状态">
          <el-radio-group v-model="listQuery.state">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button v-for="(item,index) in getEnumList('CommonEnableDisable')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="organizationId" label="负责部门">
          <Organization v-model="listQuery.organizationId" keyName="id" keyShow="organizationName" placeholder="负责部门" title="部门查询" :disabled="useUserStore().organization.organizationType !== '1'" />
        </el-form-item>
        <el-form-item prop="userId" label="负责用户">
          <User v-model="listQuery.userId" keyName="id" keyShow="name" placeholder="负责用户" title="用户查询" :disabled="useUserStore().organization.organizationType !== '1'" />
        </el-form-item>
      </el-form>
    </div>
    <el-row :gutter="20">
      <el-col :span="24" class="custom-title-box">
        <div class="custom-info-title">列表详情</div>
        <div>
          <el-button v-show="checkAuthByCode('')" type="primary" icon="Download" @click="handleExport">
            导出
          </el-button>
          <el-button type="primary" icon="Edit" :disabled="!checkAuthByCode('')" @click="handleAdd">
            新增
          </el-button>
        </div>
      </el-col>
    </el-row>
    <el-divider class="el-divider--horizontal-margin" />
    <el-table v-loading="listLoading"
              :key="tableKey"
              :data="list"
              :row-style="{height: '0'}"
              :cell-style="{padding: '0'}"
              border
              fit
              highlight-current-row
              tooltip-effect="dark"
              @sort-change="handleSortChange"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="39px" />
      <el-table-column align="center" type="index" label="序号" width="60px" />
      <el-table-column v-if="isDebug" align="center" label="ID" prop="id" width="60px" sortable show-overflow-tooltip />
      <el-table-column align="center" label="审批模版类型111" prop="approveType" min-width="130px" sortable show-overflow-tooltip>
        <template v-slot="{row}">
          <EnumTag :enum-list="getEnumList('ApproveType')" :enum-key="row.approveType" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="审批模版编码" prop="approveCode" min-width="150px" sortable>
        <template v-slot="{row}"><CodeTag :code="row.approveCode" /></template>
      </el-table-column>
      <el-table-column align="center" label="审批模版名称" prop="approveName" min-width="240px" sortable show-overflow-tooltip />
      <el-table-column align="center" label="优先级权重" prop="weight" min-width="120px" sortable show-overflow-tooltip />
      <el-table-column align="center" label="系统模块" prop="module" min-width="120px" sortable show-overflow-tooltip>
        <template v-slot="{row}">
          <EnumTag :enum-list="approveModuleArr" :enum-key="row.module" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="业务模块" prop="business" min-width="180px" sortable show-overflow-tooltip>
        <template v-slot="{row}">
          <EnumTag :enum-list="approveBusinessArr" :enum-key="row.business" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="状态" prop="state" min-width="80px" sortable show-overflow-tooltip>
        <template v-slot="{row}">
          <EnumTag :enum-list="getEnumList('CommonEnableDisable')" :enum-key="row.state" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="负责部门" width="120px" prop="organizationId" show-overflow-tooltip>
        <template v-slot="{row}"><LabelTag :foreignList="organizationList" :foreign-ids="row.organizationId" :foreign-label="'organizationName'" /></template>
      </el-table-column>
      <el-table-column align="center" label="负责用户" width="120px" prop="userId" show-overflow-tooltip>
        <template v-slot="{row}"><LabelTag :foreignList="userList" :foreign-ids="row.userId" :foreign-label="'name'" /></template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" width="180px" prop="createTime" sortable show-overflow-tooltip>
        <template v-slot="{row}"><DateTag :timestamp="row.createTime" /></template>
      </el-table-column>
      <el-table-column align="center" label="最后修改时间" width="180px" prop="updateTime" sortable show-overflow-tooltip>
        <template v-slot="{row}"><DateTag :timestamp="row.updateTime" /></template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="160px" fixed="right">
        <template v-slot="{row}">
          <el-button type="success" link @click="handleView(row)">查看</el-button>
          <el-button v-show="checkAuthByCode('PD0042')" type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-popconfirm confirm-button-text="确定"
                         cancel-button-text="取消"
                         :icon="WarningFilled"
                         icon-color="#626AEF"
                         title="您确定删除么？"
                         @confirm="handleDelete(row)"
                         v-if="checkAuthByCode('PD0043')">
            <template #reference>
              <el-button type="danger" link>删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-model:total="total" v-model:page="listQuery.pageNum" v-model:limit="listQuery.pageSize" @pagination="getList" />
    <el-dialog v-model="dialogVisible" :title="dialogTypeTitle" width="70%" top="2vh">内容无法显示</el-dialog>
  </div>
</template>

<script>
import baseConfig from '@/mixins/baseConfig'
import {doGet, doPost, doPut, doDelete, doGetDownload} from '@/config/http'
import {
  alertErrorMsg,
  customValidator,
  getEnv,
  getListPageSize,
  isNullOrUndefinedOrEmpty,
  notifySuccess,
  initListUpdate
} from "@/config/common";
import useUserStore from "@/store/modules/user";
import initListStore from '@/store/modules/initList'
import InputTagDialog from "@/components/InputTag/inputTagDialog.vue";
import SvgIcon from "@/components/SvgIcon/index.vue";
import User from "@/views/components/base/selectUser.vue";
import Organization from "@/views/components/base/selectOrganization.vue";
import {getUserId} from "@/config/cookie";

const emptyObj = {
  approveCode: null, // 审批模版编码
  approveName: null, // 审批模版名称
  state: '1', // 状态
  id: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  deleted: null,
  version: null
}

const emptyApproveNode = {
  approveName: '审批节点1',
  approveType: '',
  approveOrgId: null,
  approveUserId: null,
  nodeIdx: 1,
}

export default {
  name: 'approve_nocache',
  components: {Organization, User, SvgIcon, InputTagDialog},
  mixins: [baseConfig],
  data() {
    return {
      svc: 'icims-api',
      obj: Object.assign({}, emptyObj),
      routes: [],
      nameOfPermission: null,
      dialogVisible: false,
      dialogType: 'add',
      dialogTypeTitle: '新增',
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: false,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        sortField: 'id',
        sortType: 'desc',
        approveType: null,
        approveCode: null,
        approveName: null,
        state: null,
        organizationId: useUserStore().organization.organizationType !== '1' ? useUserStore().organization.id : '',
        userId: useUserStore().organization.organizationType !== '1' ? getUserId() : '',
        module: null,
        business: null,
        weight: null,
        createTimeStart: null,
        createTimeEnd: null,
        updateTimeStart: null,
        updateTimeEnd: null,
      },
      selectionList: [],
      dialogFormVisible: false,
      dialogStatus: '',
      rules: {
        approveType: [{ required: true, validator: customValidator, min: 1, max: 20, label: '审批模版类型', trigger: ['blur', 'change'] }],
        approveCode: [{ required: false, validator: customValidator, min: 0, max: 100, label: '审批模版编码', trigger: ['blur', 'change'] }],
        approveName: [{ required: true, validator: customValidator, min: 1, max: 200, label: '审批模版名称', trigger: ['blur', 'change'] }],
        state: [{ required: false, validator: customValidator, min: 0, max: 20, label: '状态', trigger: ['blur', 'change'] }],
        organizationId: [{ required: false, validator: customValidator, min: 0, max: 20, label: '所属部门', trigger: ['blur', 'change'] }],
        userId: [{ required: false, validator: customValidator, min: 0, max: 20, label: '所属用户', trigger: ['blur', 'change'] }],
        module: [{ required: false, validator: customValidator, min: 0, max: 20, label: '系统模块', trigger: ['blur', 'change'] }],
        business: [{ required: false, validator: customValidator, min: 0, max: 20, label: '业务模块', trigger: ['blur', 'change'] }],
        weight: [{ required: false, validator: customValidator, min: 0, max: 9, label: '优先级权重', trigger: ['blur', 'change'] }],
      },
      approveNodeNum: 1,
      userList: initListStore().userList,
      organizationList: initListStore().organizationList,
      approveConfigList: initListStore().approveConfigList,// 审批配置
      // userList: [],
      // organizationList: [],
      // approveConfigList: [],// 审批配置
      approveNodeList: [ Object.assign({}, emptyApproveNode) ],
    }
  },
  computed: {
    routesData() {
      return this.routes
    },
    approveModuleArr() {
      return this.approveConfigList
    },
    approveBusinessArr() {
      if (isNullOrUndefinedOrEmpty(this.listQuery.module)) {
        return []
      }
      return this.approveConfigList[this.listQuery.module].children
    },
  },
  created() {
    this.nameOfPermission = 'approveTemplate'
    this.getFavorite(this.nameOfPermission)?.then(res => this.userFavorites = res)
    this.getList()
    // this.initList()
  },
  methods: {
    getListPageSize,
    useUserStore,
    // async initList() {
    //   let p1 = doGet(this.svc, '/user/page', {pageSize: getListPageSize()}, false)
    //   let p2 = doGet(this.svc, '/organization/page', {pageSize: getListPageSize()}, false)
    //   let p3 = doGet(this.svc, '/customApprove/approveConfig', {}, false)
    //   let resArray = await Promise.all([p1, p2, p3])
    //   this.userList = resArray[0]['records']
    //   this.organizationList = resArray[1]['records']
    //   this.approveConfigList = resArray[2]
    // },
    addApproveNode() {
      if (this.approveNodeList.length >= 5) {
        return
      }
      let o = Object.assign({}, emptyApproveNode)
      let nodeIdx = this.approveNodeList.length + 1
      o.nodeIdx = nodeIdx
      o.approveName = '审批节点' + nodeIdx
      this.approveNodeList.push(o)
    },
    delApproveNode(nodeIdx) {
      let idx = this.approveNodeList.findIndex(item => item.nodeIdx === nodeIdx)
      this.approveNodeList.splice(idx, 1)
      for (let i in this.approveNodeList) {
        this.approveNodeList[i].nodeIdx = (parseInt(i) + 1)
        this.approveNodeList[i].approveName = '审批节点' + (parseInt(i) + 1)
      }
    },
    getList() {
      this.listLoading = true
      doGet(this.svc, '/approve/page', this.listQuery).then(res => {
        this.listLoading = false
        this.list = res['records']
        this.total = parseInt(res['total'])
      }).catch(e => {
        console.error(e)
        this.listLoading = false
      })
    },
    handleResetQuery() {
      this.resetForm("listQuery")
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      notifySuccess('操作成功')
      row.status = status
    },
    handleSelectionChange(data) {
      this.selectionList = data
    },
    handleSortChange(data) {
      const { prop, order } = data
      this.listQuery.sortField = prop
      this.listQuery.sortType = order === 'ascending' ? 'asc' : 'desc'
      this.handleFilter()
    },
    handleEdit(row) {
      this.goTargetByName('approveTemplateEdit', {id: row.id, oper: 'edit'})
    },
    handleView(row) {
      this.goTargetByName('approveTemplateEdit', {id: row.id, oper: 'view'})
    },
    handleAdd() {
      this.goTargetByName('approveTemplateEdit', {oper: 'add'})
    },
    handleExport() {
      doGetDownload(this.svc, '/approve/export', this.listQuery)
    },
    handleDelete(row) {
      doDelete(this.svc, '/approve/' + row.id, {}).then(_ => {
        notifySuccess('操作成功')
        this.getList()
        initListUpdate('approveList', '/approve/page')
      })
    },
    async doConfirm(formName) {
      let v = await this.$refs[formName].validate().catch((err)=>{return err})
      if (v !== true) {
        alertErrorMsg('表单验证不通过，请检查数据。')
        return
      }
      let users = []
      let orgs = []
      for (let i in this.approveNodeList) {
        let num = parseInt(i) + 1
        if (!this.approveNodeList[i].approveType) {
          alertErrorMsg('请选择审批节点类型')
          return
        }
        this.obj["approve" + num + "Type"] = this.approveNodeList[i].approveType
        this.obj["approve" + num + "Name"] = this.approveNodeList[i].approveName
        if (this.approveNodeList[i].approveType === '1') {
          if (!this.approveNodeList[i].approveOrgId) {
            alertErrorMsg('请选择组织架构')
            return
          }
          if (orgs.indexOf(this.approveNodeList[i].approveOrgId) > -1) {
            alertErrorMsg('组织架构重复')
            return
          }
          orgs.push(this.approveNodeList[i].approveOrgId)
        }
        this.obj["approve" + num + "OrgId"] = this.approveNodeList[i].approveOrgId
        if (this.approveNodeList[i].approveType === '2') {
          if (!this.approveNodeList[i].approveUserId) {
            alertErrorMsg('请选择用户')
            return
          }
          if (users.indexOf(this.approveNodeList[i].approveUserId) > -1) {
            alertErrorMsg('用户重复')
            return
          }
          users.push(this.approveNodeList[i].approveUserId)
        }
        this.obj["approve" + num + "UserId"] = this.approveNodeList[i].approveUserId
      }
      switch (this.dialogType) {
        case 'add':
          doPost(this.svc, '/approve/add', this.obj).then(() => {
            notifySuccess('操作成功')
            this.getList()
            this.dialogVisible = false
          })
          break;
        case 'edit':
          doPut(this.svc, '/approve/modify', this.obj).then(() => {
            notifySuccess('操作成功')
            this.getList()
            this.dialogVisible = false
          })
          break;
      }
    },
  }
}
</script>
